package com.example.timer_show;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import yuku.ambilwarna.AmbilWarnaDialog;

public class MainActivity extends AppCompatActivity {
    private Switch notificationSwitch;
    private Switch overlaySwitch;
    private RadioGroup timeFormatGroup;
    private NotificationManager notificationManager;
    private static final String CHANNEL_ID = "time_channel";
    private static final int NOTIFICATION_ID = 1;
    private Timer notificationTimer;
    private View textColorPreview;
    private View bgColorPreview;
    private SeekBar bgAlpha;
    private TextView alphaValue;
    private int textColor = Color.WHITE;
    private int bgColor = Color.BLACK;
    private int bgAlphaValue = 128;
    private LinearLayout customFormatLayout;
    private EditText customFormatInput;
    private TextView formatPreview;
    private String currentTimeFormat = "HH:mm:ss";
    private static final String PREFS_NAME = "TimeShowPrefs";
    private static final String KEY_TEXT_COLOR = "textColor";
    private static final String KEY_BG_COLOR = "bgColor";
    private static final String KEY_BG_ALPHA = "bgAlpha";
    private static final String KEY_TIME_FORMAT = "timeFormat";
    private static final String KEY_FORMAT_TYPE = "formatType";
    private static final String KEY_NOTIFICATION_ON = "notificationOn";
    private static final String KEY_OVERLAY_ON = "overlayOn";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化所有视图引用
        notificationSwitch = findViewById(R.id.switchNotification);
        overlaySwitch = findViewById(R.id.switchOverlay);
        timeFormatGroup = findViewById(R.id.timeFormatGroup);
        customFormatLayout = findViewById(R.id.customFormatLayout);
        customFormatInput = findViewById(R.id.customFormatInput);
        formatPreview = findViewById(R.id.formatPreview);
        textColorPreview = findViewById(R.id.textColorPreview);
        bgColorPreview = findViewById(R.id.bgColorPreview);
        bgAlpha = findViewById(R.id.bgAlpha);
        alphaValue = findViewById(R.id.alphaValue);

        // 设置默认选中的时间格式
        timeFormatGroup.check(R.id.format24h);
        customFormatLayout.setVisibility(View.GONE);

        createNotificationChannel();

        // 恢复保存的设置
        loadSettings();

        // 设置监听器
        setupListeners();

        // 初始化颜色预览
        textColorPreview.setBackgroundColor(textColor);
        updateBgColorPreview();
        updateAlphaText();
        updateTimePreview();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String name = "Time Display";
            String description = "Displays current time";
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            
            notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    private void startTimeNotification() {
        if (notificationTimer != null) {
            notificationTimer.cancel();
        }
        
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setOngoing(true)
                .setPriority(NotificationCompat.PRIORITY_LOW);

        notificationTimer = new Timer();
        notificationTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                builder.setContentTitle(getCurrentTimeString());
                notificationManager.notify(NOTIFICATION_ID, builder.build());
            }
        }, 0, 1000);
    }

    private void stopTimeNotification() {
        if (notificationTimer != null) {
            notificationTimer.cancel();
            notificationTimer = null;
        }
        notificationManager.cancel(NOTIFICATION_ID);
    }

    private String getCurrentTimeString() {
        try {
            return new SimpleDateFormat(currentTimeFormat, Locale.getDefault()).format(new Date());
        } catch (IllegalArgumentException e) {
            return "格式错误";
        }
    }

    private void requestOverlayPermission() {
        Intent intent = new Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + getPackageName())
        );
        startActivityForResult(intent, 0);
    }

    private void startOverlayService() {
        Intent intent = new Intent(this, OverlayService.class);
        intent.putExtra("timeFormat", currentTimeFormat);
        intent.putExtra("textColor", textColor);
        intent.putExtra("bgColor", bgColor);
        intent.putExtra("bgAlpha", bgAlphaValue);
        startService(intent);
    }

    private void updateTimeDisplay() {
        if (notificationSwitch.isChecked()) {
            startTimeNotification();
        }
        if (overlaySwitch.isChecked() && Settings.canDrawOverlays(this)) {
            startOverlayService();
        }
    }

    private void showColorPicker(boolean isTextColor) {
        AmbilWarnaDialog dialog = new AmbilWarnaDialog(
                this,
                isTextColor ? textColor : bgColor,
                new AmbilWarnaDialog.OnAmbilWarnaListener() {
                    @Override
                    public void onOk(AmbilWarnaDialog dialog, int color) {
                        if (isTextColor) {
                            textColor = color;
                            textColorPreview.setBackgroundColor(color);
                        } else {
                            bgColor = color;
                            updateBgColorPreview();
                        }
                        startOverlayService();
                        saveSettings();
                    }

                    @Override
                    public void onCancel(AmbilWarnaDialog dialog) {}
                }
        );
        dialog.show();
    }

    private void updateBgColorPreview() {
        int color = Color.argb(
                bgAlphaValue,
                Color.red(bgColor),
                Color.green(bgColor),
                Color.blue(bgColor)
        );
        bgColorPreview.setBackgroundColor(color);
    }

    private void updateAlphaText() {
        int percentage = (int) ((bgAlphaValue / 255.0f) * 100);
        alphaValue.setText("背景透明度: " + percentage + "%");
    }

    private void updateTimePreview() {
        try {
            String preview = new SimpleDateFormat(currentTimeFormat, Locale.getDefault())
                    .format(new Date());
            formatPreview.setText("预览: " + preview);
            formatPreview.setError(null);
        } catch (IllegalArgumentException e) {
            formatPreview.setText("预览: 格式错误");
            formatPreview.setError("时间格式不正确");
        }
    }

    private void setupListeners() {
        notificationSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                startTimeNotification();
            } else {
                stopTimeNotification();
            }
            saveSettings();
        });

        overlaySwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                if (!Settings.canDrawOverlays(this)) {
                    requestOverlayPermission();
                } else {
                    startOverlayService();
                }
            } else {
                stopService(new Intent(this, OverlayService.class));
            }
            saveSettings();
        });

        timeFormatGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.format24h) {
                currentTimeFormat = "HH:mm:ss";
                customFormatLayout.setVisibility(View.GONE);
            } else if (checkedId == R.id.format12h) {
                currentTimeFormat = "hh:mm:ss a";
                customFormatLayout.setVisibility(View.GONE);
            } else if (checkedId == R.id.formatCustom) {
                currentTimeFormat = customFormatInput.getText().toString();
                customFormatLayout.setVisibility(View.VISIBLE);
            }
            updateTimePreview();
            updateTimeDisplay();
            saveSettings();
        });

        customFormatInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (timeFormatGroup.getCheckedRadioButtonId() == R.id.formatCustom) {
                    currentTimeFormat = s.toString();
                    updateTimePreview();
                    updateTimeDisplay();
                    saveSettings();
                }
            }
        });

        findViewById(R.id.btnTextColor).setOnClickListener(v -> showColorPicker(true));
        findViewById(R.id.btnBgColor).setOnClickListener(v -> showColorPicker(false));

        bgAlpha.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                bgAlphaValue = progress;
                updateBgColorPreview();
                updateAlphaText();
                if (overlaySwitch.isChecked()) {
                    startOverlayService();
                }
                saveSettings();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    private void loadSettings() {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        
        // 恢复颜色设置
        textColor = settings.getInt(KEY_TEXT_COLOR, Color.WHITE);
        bgColor = settings.getInt(KEY_BG_COLOR, Color.BLACK);
        bgAlphaValue = settings.getInt(KEY_BG_ALPHA, 128);
        bgAlpha.setProgress(bgAlphaValue);
        
        // 恢复时间格式设置
        currentTimeFormat = settings.getString(KEY_TIME_FORMAT, "HH:mm:ss");
        int formatType = settings.getInt(KEY_FORMAT_TYPE, R.id.format24h);
        timeFormatGroup.check(formatType);
        
        if (formatType == R.id.formatCustom) {
            customFormatLayout.setVisibility(View.VISIBLE);
            customFormatInput.setText(currentTimeFormat);
        } else {
            customFormatLayout.setVisibility(View.GONE);
        }
        
        // 恢复开关状态（先设置状态，再触发服务）
        boolean notificationOn = settings.getBoolean(KEY_NOTIFICATION_ON, false);
        boolean overlayOn = settings.getBoolean(KEY_OVERLAY_ON, false);
        
        notificationSwitch.setChecked(notificationOn);
        overlaySwitch.setChecked(overlayOn);
        
        // 更新UI和服务
        updateBgColorPreview();
        updateAlphaText();
        updateTimePreview();
        
        // 启动相应的服务
        if (notificationOn) {
            startTimeNotification();
        }
        if (overlayOn && Settings.canDrawOverlays(this)) {
            startOverlayService();
        }
    }

    private void saveSettings() {
        SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
        
        // 保存颜色设置
        editor.putInt(KEY_TEXT_COLOR, textColor);
        editor.putInt(KEY_BG_COLOR, bgColor);
        editor.putInt(KEY_BG_ALPHA, bgAlphaValue);
        
        // 保存时间格式设置
        editor.putString(KEY_TIME_FORMAT, currentTimeFormat);
        editor.putInt(KEY_FORMAT_TYPE, timeFormatGroup.getCheckedRadioButtonId());
        
        // 保存开关状态
        editor.putBoolean(KEY_NOTIFICATION_ON, notificationSwitch.isChecked());
        editor.putBoolean(KEY_OVERLAY_ON, overlaySwitch.isChecked());
        
        editor.apply();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 检查并更新悬浮窗权限状态
        if (overlaySwitch.isChecked() && !Settings.canDrawOverlays(this)) {
            overlaySwitch.setChecked(false);
            saveSettings();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveSettings();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (notificationTimer != null) {
            notificationTimer.cancel();
        }
        stopService(new Intent(this, OverlayService.class));
    }
}